package com.fsoft.core.org.service.impl;

import java.math.BigDecimal;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.fsoft.core.Global;
import com.fsoft.core.common.QueryParam;
import com.fsoft.core.common.base.service.impl.BaseServiceImpl;
import com.fsoft.core.context.FSContext;
import com.fsoft.core.org.entity.SysOrg;
import com.fsoft.core.org.mapper.SysOrgMapper;
import com.fsoft.core.org.service.SysOrgService;
import com.fsoft.core.utils.OgnlUtils;

/**
 * F-Soft
 * 
 * @package com.fsoft.core.org.service.impl
 * @author Fish
 * @email it.fish2010@foxmail.com
 * @date 2019-11-16
 * @CopyRight © F-Soft
 **/
@Service("organizeService")
@Transactional
public class SysOrgServiceImpl extends BaseServiceImpl<SysOrg> implements SysOrgService {
	@Autowired
	private SysOrgMapper mapper;

	@Override
	public SysOrg getOrgByCode(String code) throws Exception {
		return mapper.selectByCode(code);
	}

	/**
	 * 默认所属组织的全部下级单位
	 */
	@Override
	public List<SysOrg> findList(QueryParam query) throws Exception {
		if (!FSContext.getInstance().getUser().isSuperAdmin())
			query.put(Global.F_ORGID, FSContext.getInstance().getUser().getOrgId());
		return super.findList(query);
	}

	@Override
	public int save(SysOrg param) throws Exception {
		param.setParents(param.getId());
		if (StringUtils.isBlank(param.getId()))
			param.setId(OgnlUtils.randomUpperCaseId());
		if (StringUtils.isNotBlank(param.getParentId())) {
			SysOrg pOrg = getEntity(param.getParentId());
			if (OgnlUtils.isNotEmpty(pOrg)) {
				param.setParents(pOrg.getParents() + "_" + param.getId());
			}
		}
		return super.save(param);
	}

	@Override
	public int modify(SysOrg param) throws Exception {
		SysOrg entity = getEntity(param.getId());
		if (OgnlUtils.isEmpty(entity))
			throw new Exception("无法识别的单位标识[" + param.getId() + "]");
		// 如果上级节点有调整
		if (!StringUtils.equals(param.getParentId(), entity.getParentId())) {
			param.setParents(param.getId());
			if (StringUtils.isNotBlank(param.getParentId())) {
				SysOrg pOrg = getEntity(param.getParentId());
				if (OgnlUtils.isNotEmpty(pOrg)) {
					param.setParents(pOrg.getParents() + "_" + param.getId());
				}
			}
		}
		return super.modify(param);
	}

	@Override
	public BigDecimal getMaxSort() throws Exception {
		BigDecimal num = mapper.selectMaxSort();
		if (num == null)
			num = BigDecimal.ZERO;
		return num.add(BigDecimal.ONE);
	}

}
